<?php

declare(strict_types=1);

namespace App\Helpers;

/**
 * 新支付
 */
class NewPayUtil
{

    //测试
    //const API_HOST = 'http://pay.meihua123.top/mapi.php';
    //const PAY_KEY = 'UK0sa5KLeUR4k69F6B4egG85625G22MR'; //key
    //const CALLBACK_URL = 'https://api.jun131419.com/callback/new_pay';//回调链接
    //const SHOP_ID = 1002;


    //正式
    const API_HOST = 'http://payapi.jun131419.com/mapi.php';
    const PAY_KEY = '68Py8vDYV2848aav8sd9yx6B6LyHg2A2'; //key
    const CALLBACK_URL = 'https://api.jun131419.com/callback/new_pay';//�~[~^�~C�~S��~N�
    const SHOP_ID = 1020;
    //const API_HOST = 'http://aigos.aigou.online/mapi.php';
    //const PAY_KEY = 'KgyP22X29Iyq4GXKy23qQ2x29x3XX6xY'; //key
    //const PAY_URL = 'http://pay.meihua123.top/';//支付链接
    /**
     * 充值下单
     */
    static function orderCreateNew($orderInfo = [], $channel = '')
    {

	//return $orderInfo;	    
        $orderId = $orderInfo['out_trade_no'] ?? date('YmdHis') . '_' . mt_rand(1000, 9999);
        $data = [
            'pid' => self::SHOP_ID,
            'type' => $orderInfo['type'],
            'out_trade_no' => $orderInfo['out_trade_no'],
            'notify_url' => self::CALLBACK_URL,
            'name' => 'VIP会员',
            'money' => $orderInfo['money'] / 100,        
	    'clientip'=> $orderInfo['clientip'],
	    'device' => 'mobile',
	];
   // file_put_contents("0617.txt",json_encode($data));
        //$md5Key = self::PAY_KEY;
        //$str = urldecode(http_build_query($data)) . $md5Key;
	$str = self::getSign($data);
	//return $str;
	log_user_result($orderId, $str);
	$data['sign'] = $str;
	$data['sign_type'] = 'MD5';
//	return $data;
	$result = self::curlRequest(self::API_HOST, $data);
        return $result;
    }

     /*
     * 发送请求
     * @param $url
     * @param $param
     * @return bool|mixed
     * @throws Exception
     */
    static function curlRequest($url, $postData = array(), $json = true)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($postData) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $info = curl_getinfo($ch);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    // 计算签名
    static function getSign($param){
	ksort($param);
	reset($param);
	$signstr = '';

	foreach($param as $k => $v){
	    if($k != "sign" && $k != "sign_type" && $v!=''){
		$signstr .= $k.'='.$v.'&';
	    }
	}
	$signstr = substr($signstr,0,-1);
	$signstr .= self::PAY_KEY;
	$sign = md5($signstr);
	return $sign;
     }

}
